use std::{fs, net::TcpListener, process::Command, sync::OnceLock};

use dioxus_logger::tracing::info;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct WxUser {
    pub wx_id: String,
    wx_account: String,
    pub nick_name: String,
    avatar_url: String,
    nation: String,
    province: String,
    city: String,
    mobile: String,
    // 性别
    // - 0 未设置
    // - 1 男
    // - 2 女
    gender: u8,
    // 登录设备
    device: String,
    // 缓存目录
    cache_dir: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BzUser {
    pub nickname: String,
}

pub static USER: OnceLock<WxUser> = OnceLock::new();

fn find_free_port() -> Option<u16> {
    TcpListener::bind("127.0.0.1:0")
        .ok()
        .map(|listener| listener.local_addr().unwrap().port())
}

pub fn get_port() -> (&'static u16, &'static u16) {
    static SEND_PORT: OnceLock<u16> = OnceLock::new();
    static LISTEN_PORT: OnceLock<u16> = OnceLock::new();

    // (
    //     SEND_PORT.get_or_init(|| find_free_port().expect("Failed to find free port for sending")),
    //     LISTEN_PORT
    //         .get_or_init(|| find_free_port().expect("Failed to find free port for listening")),
    // )

    (
        SEND_PORT.get_or_init(|| 8999),
        LISTEN_PORT.get_or_init(|| 9000),
    )
}

fn init_wx() {
    let inject_tool_path = "./tool/dfg/inject_tool.exe";

    if !fs::metadata(inject_tool_path).is_ok() {
        eprintln!("Error: {} does not exist", inject_tool_path);
        std::process::exit(1);
    }

    let (send, listen) = get_port();

    let output = Command::new(inject_tool_path)
        .arg("start")
        .arg(send.to_string())
        .arg(format!("--my_port={listen}"))
        .output()
        .expect("Error executing command");

    info!("注入结果:{output:?}");
}
